import React, { FC, useState } from 'react';
import ProTable, { ProColumns, ActionType } from '@/components/ProTable';
import styles from './index.less';
import { useModel } from 'umi';
import { TableListItem } from '@/pages/Card/useCardModel';
import ToolBar from './components/Toolbar';
import IconFont from '@/components/IconFont';
import ModalContent from './components/Modal';
import useHoxModel from '../../useHoxModel';
import { modelName } from '../../index';
import { useUpdateEffect } from 'ahooks';
import { Dropdown, Menu } from 'antd';

//定义setTimeout返回类型
// type TimerHandle = ReturnType<typeof setTimeout>;

interface CardProps {
  actionRef: React.MutableRefObject<ActionType | undefined>;
}

const BlankCard: FC<CardProps> = ({ actionRef }) => {
  const {
    getDoorList,
    currentCode,
    getUserFormAreaList,
    selectedRowKeys,
    getFormAreaList,
    getCardUserListByDoor,
    getDoorListByUser,
    dispatch,
    getUserList,
    currentPageType,
  } = useHoxModel((model) => [model.selectedRowKeys, model.currentCode, model.currentPageType]);
  const { showModal } = useModel('useCommonModal', (model) => ({ showModal: model.showModal }));

  useUpdateEffect(() => {
    actionRef.current?.reloadAndRest();
  }, [currentCode]);

  const menu = (record: { id: number }) => {
    const onClick = async ({ key }: { key: string }) => {
      switch (key) {
        case 'permissionsConfig':
          dispatch({ info: record });
          getUserFormAreaList();
          getCardUserListByDoor({ id: record.id });
          showModal(modelName + 'permissionsConfig');
          break;
        case 'permissionsDetail':
          dispatch({ info: record });
          showModal(modelName + 'detail');
          break;
      }
    };
    return (
      <Menu onClick={onClick}>
        <Menu.Item key={'permissionsConfig'}>
          <IconFont type={'iconbianji'} style={{ fontSize: '14px' }} />
          <span>权限配置</span>
        </Menu.Item>
        <Menu.Item key={'permissionsDetail'}>
          <IconFont type={'iconshanchu1'} style={{ fontSize: '14px' }} />
          <span>权限详情</span>
        </Menu.Item>
      </Menu>
    );
  };
  const userMenu = (record: { id: number }) => {
    const onClick = async ({ key }: { key: string }) => {
      switch (key) {
        case 'permissionsConfig':
          dispatch({ info: record });
          getFormAreaList();
          getDoorListByUser({ id: record.id });
          showModal(modelName + 'permissionsConfig');
          break;
        case 'permissionsDetail':
          dispatch({ info: record });
          showModal(modelName + 'detail');
          break;
      }
    };
    return (
      <Menu onClick={onClick}>
        <Menu.Item key={'permissionsConfig'}>
          <IconFont type={'iconquanxianpeizhi'} style={{ fontSize: '14px' }} />
          <span>权限配置</span>
        </Menu.Item>
        <Menu.Item key={'permissionsDetail'}>
          <IconFont type={'iconquanxianxiangqing'} style={{ fontSize: '14px' }} />
          <span>权限详情</span>
        </Menu.Item>
      </Menu>
    );
  };
  const userColumns: ProColumns<TableListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      valueType: 'index',
      width: '10%',
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      align: 'center',
    },
    {
      title: '姓名',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '手机',
      align: 'center',
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: '身份证',
      align: 'center',
      dataIndex: 'idCard',
      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'option',
      width: '10%',
      valueType: 'option',
      render: (_, record, index) => [
        <Dropdown overlay={userMenu(record)} key={index.toString(36) + index}>
          <a key={'loss'} className={styles['operation']}>
            <IconFont type={'iconcaozuo2'} />
          </a>
        </Dropdown>,
      ],
    },
  ];
  const doorColumns: ProColumns<TableListItem>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '门状态',
      dataIndex: 'doorStatus',
      valueEnum: {
        1: { text: '离线' },
        0: { text: '在线' },
        '': { text: '全部' },
      },
      hideInTable: true,
    },
    {
      title: '门名称',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '所在区域',
      align: 'center',
      dataIndex: 'regionName',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '控制器名称',
      align: 'center',
      dataIndex: 'controllerName',
      hideInSearch: true,
    },
    {
      title: '计划模板',
      align: 'center',
      dataIndex: 'planMode',
      hideInSearch: true,
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'status',
      render: (text: React.ReactNode) => {
        const valueEnum = {
          1: '在线',
          0: '离线',
        };
        return (
          <>
            {text !== null ? (
              <span className={Number(text) === 0 ? styles['online'] : styles['offline']}>
                {valueEnum[Number(text)]}
              </span>
            ) : (
              '-'
            )}
          </>
        );
      },

      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'option',
      width: '6%',
      valueType: 'option',
      render: (_, record, index) => [
        <Dropdown overlay={menu(record)} key={index.toString(36) + index}>
          <a key={'loss'} className={styles['operation']}>
            <IconFont type={'iconcaozuo2'} />
          </a>
        </Dropdown>,
      ],
    },
  ];
  const [columns, setColumns] = useState(currentPageType === 'door' ? doorColumns : userColumns);
  useUpdateEffect(() => {
    actionRef.current?.reloadAndRest();
    setColumns(currentPageType === 'door' ? doorColumns : userColumns);
  }, [currentPageType]);

  return (
    <div className={styles['container']}>
      <ProTable<TableListItem>
        columns={columns}
        request={async (params: { [key: string]: any }) => {
          let data = null;
          if (currentPageType === 'user') {
            data = await (currentCode &&
              getUserList({
                keyword: params.keyword || undefined,
                number: params.pageSize,
                page: params.current,
                code: currentCode,
                status: params.doorStatus || undefined,
              }));
          } else {
            data = await (currentCode &&
              getDoorList({
                keyword: params.keyword || undefined,
                number: params.pageSize,
                page: params.current,
                code: currentCode,
                status: params.doorStatus || undefined,
              }));
          }
          return await {
            data: (currentCode && data?.list) || [],
            success: true,
            total: (currentCode && data?.count) || 0,
          };
        }}
        rowKey="id"
        rowSelection={{
          selectedRowKeys,
          onChange: (selectedRowKeys) => {
            dispatch({ selectedRowKeys });
          },
        }}
        search={false}
        options={{
          search: {
            name: 'keyword',
          },
        }}
        tableAlertRender={false}
        actionRef={actionRef}
        dateFormatter="string"
        headerTitle={false}
        toolBarRender={() => [<ToolBar actionRef={actionRef} />]}
      />
      <ModalContent actionRef={actionRef} />
    </div>
  );
};
export default BlankCard;
